package com.biu.zone;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.biu.zone.application.ShotApp;
import com.biu.zone.common.bean.ScreenAppBean;
import com.biu.zone.common.utils.PackageUtil;
import com.biu.zone.service.FloatingWindowService1;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import cn.net.bhb.base.utils.L;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    RecyclerView recyclerview;
    ImageView ivHead;
    TextView tvName;
    TextView tvStart;

    private BaseQuickAdapter adapter;
    private WindowManager mWm;
    private int result = 0;
    private Intent intent = null;
    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<ScreenAppBean> notSystemAppList = new ArrayList<>();

    private static final int FLOATING_SERVICE = 0x111;
    private static final int REQUEST_MEDIA_PROJECTION = 0x333;
    private static final int PERM_CODE = 0x444;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //        ButterKnife.bind(this);

        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "需要存储权限", PERM_CODE, perms);
        }

        startFloatingService();
        initView();
        initRecycler();
        initData();
        initListener();

    }

    private void initView() {
        recyclerview = findViewById(R.id.recyclerview);
        ivHead = findViewById(R.id.iv_head);
        tvName = findViewById(R.id.tv_name);
        tvStart = findViewById(R.id.tv_start);
    }

    private void initRecycler() {
        recyclerview.setAdapter(adapter = new BaseQuickAdapter<ScreenAppBean, BaseViewHolder>
                (R.layout.item_app, null) {
            @Override
            protected void convert(BaseViewHolder helper, ScreenAppBean item) {
                helper.setText(R.id.tv_name, item.getName());
                helper.setImageDrawable(R.id.iv_icon, item.getIcon());
            }
        });
        adapter.setOnItemClickListener((adapter, view, position) -> {
            ScreenAppBean bean = (ScreenAppBean) adapter.getData().get(position);
            Intent intent = PackageUtil.getAppOpenIntentByPackageName(this, bean.getPackageName());
            startActivity(intent);
        });
    }

    private void initData() {
        getAppList();
        if (!notSystemAppList.isEmpty()) {
            ivHead.setImageDrawable(notSystemAppList.get(0).getIcon());
            tvName.setText(notSystemAppList.get(0).getName());
        }
    }

    private void initListener() {
        tvStart.setOnClickListener(v -> {
            if (intent != null && result != 0) {
                ((ShotApp) getApplication()).setResult(result);
                ((ShotApp) getApplication()).setIntent(intent);
                Intent intent = new Intent(getApplicationContext(), FloatingWindowService1.class);
                startService(intent);
            } else {
                //弹出dialog询问用户是否授权应用捕捉屏幕，同时覆写onActivityResult()获取授权结果
                MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FLOATING_SERVICE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "请授权", Toast.LENGTH_SHORT).show();
                }
            }

        } else if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                return;
            } else if (data != null && resultCode != 0) {
                result = resultCode;
                intent = data;
                ((ShotApp) getApplication()).setResult(resultCode);
                ((ShotApp) getApplication()).setIntent(data);
                Intent intent = new Intent(getApplicationContext(), FloatingWindowService1.class);
                startService(intent);

                finish();
            }
        }

    }

    private void getAppList() {
        PackageManager pm = getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            // 判断系统/非系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) // 非系统应用
            {
                L.e("MainActivity.getAppList, packageInfo=" + packageInfo.packageName);
                ScreenAppBean bean = new ScreenAppBean();
                bean.setIcon(packageInfo.applicationInfo.loadIcon(pm));
                bean.setName(packageInfo.applicationInfo.loadLabel(pm).toString());
                bean.setPackageName(packageInfo.packageName);
                notSystemAppList.add(bean);
            } else {
                // 系统应用
            }
        }

        adapter.setNewData(notSystemAppList);
    }


    private void startFloatingService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "请授权", Toast.LENGTH_SHORT).show();
                startActivityForResult(
                        new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())),
                        FLOATING_SERVICE
                );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @AfterPermissionGranted(PERM_CODE)
    private void requestPermissions4Camera() {
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            EasyPermissions.requestPermissions(this, "需要存储权限", PERM_CODE, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (!EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("截屏")
                    .setRationale("需要存储权限")
                    .setPositiveButton("确定")
                    .setNegativeButton("取消")
                    .setThemeResId(R.style.Theme_AppCompat_Light_Dialog_Alert)
                    .build()
                    .show();
        }
    }
}
